import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const store = new Vuex.Store({
  // 公共的数据仓库
  state: {
    count: 0,
    list: [],
    // 购物列表数据
    shopAllList: [],
    // 购物车数据
    shopCarList: []
  },
  mutations: {
    addCount (state) {
      state.count++
    },
    setList (state, data) {
      console.log('data', data)
      // state.list = [1,2,3,4,5]
      state.list.push(data)
    },
    // 增加购物列表数据
    addShopList (state, shopData) {
      console.log('数据仓局', shopData)
      state.shopAllList.push(shopData)
    },
    // 增加购物车列表数据
    addShopCarList (state, shopData) {
      state.shopCarList.push(shopData)
    },
    addCount (state, shopId) {
      // 通过传进来的参数找到该商品的下标
      let index = state.shopCarList.findIndex(item => {
        return item.id === shopId
      })

      // 通过下标拿到商品的数量，并且自增
      state.shopCarList[index].count++
    },
    deleteCount (state, shopId) {
      let index = state.shopCarList.findIndex(item => {
        return item.id === shopId
      })

      if (state.shopCarList[index].count === 1) {
        return
      }

      state.shopCarList[index].count--
    }
  }
})

export default store
